package com.cos.shop.dao.impl;

import com.cos.shop.dao.ProductDao;
import com.cos.shop.entity.Product;
import com.cos.shop.entity.Type;
import com.cos.shop.util.JDBCUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import sun.security.krb5.internal.PAData;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author: COS
 * @time: 2022/2/24 9:07
 * @description:
 */
public class ProductDaoImpl implements ProductDao {
    private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public Product getProductById(int pid) throws SQLException, InvocationTargetException, IllegalAccessException {
        Map<String, Object> query = qr.query("select p.pid,p.pimage,p.pinfo,p.pname,p.pprice," +
                        "p.pstate,p.ptime,p.tid,t.tname from product p ,type t where p.tid= t.tid and p.pid=?",
                new MapHandler(), pid);
        if (query != null) {
            //创建 product
            Product p = new Product();
            //创建 type
            Type type = new Type();
            //数据的自动封装 使用BeanUtils  entity pojo vo->viewObject
            BeanUtils.populate(p, query);
            BeanUtils.populate(type, query);
            //手动把type对象封装进product
            p.setType(type);
            return p;
        }
        return null;
    }

    @Override
    public List<Product> getProductPageByTid(int typeid, int startRow, int pages) throws SQLException {
        return qr.query("select * from product where tid=? limit ?,?",new BeanListHandler<>(Product.class),
                typeid,startRow, pages);
    }

    @Override
    public Long getProductCount(int typeid) throws SQLException {
        return qr.query("select count(pid) from product where tid=?",new ScalarHandler<>(),typeid);
    }

    @Override
    public List<Product> getProductByTid(int typeid) throws SQLException {
        return qr.query("select * from product where tid=?",new BeanListHandler<>(Product.class),typeid);
    }
}
